package com.cmbyc.cbslink.example;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;


public class MyX509TrustManager2 implements X509TrustManager{
	
	X509TrustManager x509TrustManager;
	
	

	public MyX509TrustManager2(String certPath)throws Exception {
	
		KeyStore ks = KeyStore.getInstance("JKS");
		//ks.load(new FileInputStream(keystoreFile),pass.toCharArray());
		ks.load(null,null);
		CertificateFactory cf = CertificateFactory.getInstance("X.509");

		Certificate certificate = cf.generateCertificate(new FileInputStream(certPath));

		ks.setCertificateEntry("erpcert",certificate);


		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 
        tmf.init(ks); 
        TrustManager  []tms = tmf.getTrustManagers();
        for (int i = 0; i < tms.length; i++) { 
            if (tms[i] instanceof X509TrustManager) { 
                x509TrustManager = (X509TrustManager) tms[i]; 
                return; 
            } 
        } 
        throw new Exception("Couldn't initialize"); 
		
	}

	@Override  
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
		try { 
            x509TrustManager.checkClientTrusted(chain, authType); 
        } catch (CertificateException excep) { 
        	excep.printStackTrace();
        }	

	}  
	 
	@Override  
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
		try { 
            x509TrustManager.checkServerTrusted(chain, authType); 
        } catch (CertificateException excep) { 
        	excep.printStackTrace();
        }	
           
	}  
	 
	@Override  
	public X509Certificate[] getAcceptedIssuers() {    
		return x509TrustManager.getAcceptedIssuers();  
	}  
}
